﻿//
//  GNS_Calendar.cpp
//  MobileManageSys
//
//  Created by mr.l on 16/1/16.
//
//

#include "GNS_Calendar.h"

USING_NS_CC;
#define winsize Director::getInstance()->getVisibleSize()
GNS_Calendar::GNS_Calendar()
{
    CalendarBg=0;
    TouchEventSpt=0;
    m_bIsClickWndOutSideClose=true;
    TimeLabel=0;
    Mon=0;
    year=0;
    day=0;
    pPageView=nullptr;
}
GNS_Calendar::~GNS_Calendar()
{
    
}

GNS_Calendar * GNS_Calendar::createCalendar()
{
     auto pScene = Director::getInstance()->getRunningScene();
    if (!pScene)
        return  0;
     auto pCalendar = GNS_Calendar::create();
     pScene->addChild(pCalendar);
    
    return pCalendar;
}

bool GNS_Calendar::init(){
    // 1. super init first
    if ( !Layer::init() )
    {
        return false;
    }
    /////////////////////////////
    // 2. add your codes below...
    
    LayerColor* pLayer=LayerColor::create(Color4B(0,0,0,110));
    this->addChild(pLayer,0,11);

    auto callback = [](Touch * ,Event *)
    {
        return true;
    };
    listener = EventListenerTouchOneByOne::create();
    listener->onTouchBegan = callback;
    listener->onTouchEnded =CC_CALLBACK_2(GNS_Calendar::TouchEvnets,this);
    listener->setSwallowTouches(true);
    _eventDispatcher->addEventListenerWithSceneGraphPriority(listener,this);
    
    TouchEventSpt = Sprite::create();
    TouchEventSpt->setPosition(Vec2(0, 0));
    this->addChild(TouchEventSpt);
    
    AddTimeDate();
    scheduleUpdate();
    return true;
}

void GNS_Calendar::SetCalendBgImage(std::string ImageName)
{
    CalendarBg=Sprite::create(ImageName);
    CalendarBg->setPosition(Vec2(winsize.width/2, winsize.height/2));
    this->addChild(CalendarBg);
    
    CalendarSize = CalendarBg->getContentSize();
    auto  LeftButton = Button::create("left.png","left1.png");
    LeftButton->setPosition(Vec2(CalendarSize.width*0.1,CalendarSize.height-LeftButton->getContentSize().height*0.6));
    LeftButton->setTag(1);
    LeftButton->addTouchEventListener(CC_CALLBACK_2(GNS_Calendar::BtnCallBack, this));
    CalendarBg->addChild(LeftButton);
    
    auto  RightButton = Button::create("right.png","right1.png");
    RightButton->setPosition(Vec2(CalendarSize.width*0.9,LeftButton->getPositionY()));
    RightButton->setTag(2);
    RightButton->addTouchEventListener(CC_CALLBACK_2(GNS_Calendar::BtnCallBack, this));
    CalendarBg->addChild(RightButton);
    //设置当前时间
    std::string Date=StringUtils::format("%d-%02d-%02d",year,Mon,day);
    TimeLabel = Label::createWithSystemFont(Date, "", 28);
    TimeLabel->setColor(Color3B::BLACK);
    TimeLabel->setPosition(Vec2(CalendarSize.width/2, LeftButton->getPositionY()));
    CalendarBg->addChild(TimeLabel);
    
    SetTimeDate();
}
void GNS_Calendar::SetTimeDate()
{
    pPageView = PageView::create();
    pPageView->setAnchorPoint(Vec2(0.5, 0.5));
    pPageView->setPosition(Vec2(CalendarSize.width/2,CalendarSize.height*0.4));
    pPageView->setContentSize(Size(CalendarSize.width, CalendarSize.height*0.8));
    pPageView->setBackGroundColor(Color3B::BLACK);
    CalendarBg->addChild(pPageView,20);
    pPageView->addEventListener(CC_CALLBACK_2(GNS_Calendar::pageViewEvent, this)); //3.9使用 已经被废弃了
 //pPageView->setIndicatorEnabled(true);
//添加触摸事件,暂时用不到,后面应该能用到
//    pPageView->addTouchEventListener([](Ref* Sender,Widget::TouchEventType type){
//        if (type ==Widget::TouchEventType::BEGAN) {
//
//            
//            log("Page view touch Began");
//        }else if (type ==Widget::TouchEventType::MOVED)
//        {
//            
//            log("Page view touch MOVED");
//        }else if (type==Widget::TouchEventType::ENDED)
//        {
//            
//            log("Page view touch ENDED");
//        }else{
//            
//            log("Page view touch cancelled");
//        }
//    
//    });
       int pageCount = 13;
    for (int i =1; i<pageCount; i++) {
        //添加基本容器
        auto layout = Layout::create();
        layout->setSize(pPageView->getContentSize());
        //添加元素
        std::map<int, std::vector<int > >::iterator  my_Itr;
        my_Itr= _TimeMap.find(i);
        if(my_Itr!=_TimeMap.end())
        {
           std::vector<int >_Day =   my_Itr->second;
            int y=1;
            for (auto iter = _Day.cbegin(); iter != _Day.cend(); iter++)
            {
                int x = *iter;
                auto pTimeButton = Button::create();
                pTimeButton->setTitleText(StringUtils::format("%d",x));
                pTimeButton->setTitleFontSize(28);
                pTimeButton->setTitleColor(Color3B::BLACK);
                pTimeButton->setPosition(Vec2(layout->getContentSize().width*(0.1+(y%7)*0.13), layout->getContentSize().height*(0.9-(y/7)*0.2)));
                pTimeButton->setTag(100+y);
                pTimeButton->setPropagateTouchEvents(false);
                layout->addChild(pTimeButton);
                _TimeButton.push_back(pTimeButton);
                y++;
            }
        }else{
        
        }
        pPageView->insertPage(layout,i-1);
    }
    pPageView->setCurrentPageIndex(Mon-1);
 }
void GNS_Calendar::AddTimeDate()
{
    //获取当前年份
    struct timeval now;
    struct tm* time;
    gettimeofday(&now, NULL);
    time = localtime((time_t*)&now.tv_sec);
    Mon = (int)time->tm_mon+1;
    year = time->tm_year + 1900;
    day =(int)time->tm_mday;
    log("year = %d",year);
    
    for (int i=1; i<13; i++)
    {
        std::vector<int > _DayNum;
        int MonDay=0;
        if (i==1||i==3||i==5||i==7||i==8||i==10||i==12) {
            MonDay=31;
        }else if (i==4||i==6||i==9||i==11){
            MonDay=30;
        }else if (i==2){
            if(year%4==0)
            {
                MonDay=29;
            }else{
                MonDay=28;
            }
        }
        for (int j =1;j<MonDay+1;j++) {
            _DayNum.push_back(j);
        }
        _TimeMap.insert(std::pair<int, std::vector<int > >(i,_DayNum));
    }
}
void GNS_Calendar::BtnCallBack(cocos2d::Ref *pSender, ui::Widget::TouchEventType type)
{
    auto pButton = (Button *)pSender;
    int tag = pButton->getTag();
    if (type==ui::Widget::TouchEventType::ENDED) {
        
        switch (tag) {
            case 1:
            {
                pPageView->scrollToItem(Mon-2);
                 Mon--;
                break;
            }
            case 2:
            {
                pPageView->scrollToItem(Mon);
                Mon++;
                break;
            }
            case 10:
            {
                pButton->setTitleColor(Color3B::BLACK);
                std::string pButtonText=pButton->getTitleText();
                day=atoi(pButton->getTitleText().c_str());
                TimeLabel->setString(StringUtils::format("%d-%02d-%02d",year,Mon,day));
                log("%s",pButton->getTitleText().c_str());
                this->Show(false);
                break;
            }
            default:
                break;
        }
    }else if (type==ui::Widget::TouchEventType::BEGAN)
    {
        if (tag==10) {
            pButton->setTitleColor(Color3B::RED);
        }
    }
}
void GNS_Calendar::TouchEvnets(cocos2d::Touch *pTouch, cocos2d::Event *pEvents)
{
    Point pos = pTouch->getLocation();
    if (m_bIsClickWndOutSideClose) {
        if (CalendarBg) {
            TouchEventSpt->setPosition(pos);
            
            if (!TouchEventSpt->getBoundingBox().intersectsRect(CalendarBg->getBoundingBox()))
            {
                this->Show(false);
            }
        }
    }
}
//3.9使用 3.10废弃了
void GNS_Calendar::pageViewEvent(Ref *pSender, PageView::EventType type)
{
    switch (type)
    {
        case PageView::EventType::TURNING:
        {
            PageView* pageView = dynamic_cast<PageView*>(pSender);
            CurrentPageNum=(int)pageView->getCurrentPageIndex()+1;
           
            if ((int)CurrentPageNum!=Mon) {
                Mon=(int)CurrentPageNum;
                TimeLabel->setString(StringUtils::format("%d-%02d-%02d",year,Mon,day));
                 log("滑动了,当前页码为%d",CurrentPageNum);
            }else{
                 log("没有滑动,当前页码为%d",CurrentPageNum);
            }
            
        }
            break;
            
        default:
            break;
    }

}
void GNS_Calendar::update(float dt)
{
//    log("%zd",pPageView->getCurrentPageIndex());
    CurrentPageNum = (int)pPageView->getCurrentPageIndex()+1;
    
    if ((int)CurrentPageNum!=Mon) {
        Mon=(int)CurrentPageNum;
        TimeLabel->setString(StringUtils::format("%d-%02d-%02d",year,Mon,day));
    }else{
    }

}
void GNS_Calendar::Show(bool bShow)
{
    _eventDispatcher->removeEventListener(listener);
    unscheduleUpdate();
    this->removeAllChildrenWithCleanup(!bShow);
}
std::vector<Button*> * GNS_Calendar::GetTimeButton()
{
    return &_TimeButton;
}